﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace Guru.Utilities
{
    public static class ControlExtensions
    {
        /// <summary>
        /// Find a control in the current container
        /// If not found --> find in childs(loop).
        /// </summary>
        /// <param name="container"></param>
        /// <param name="controlId"></param>
        /// <returns></returns>
        public static Control FindInnerControl(Control container, string controlId)
        {
            // Find in current container
            Control matchControl = FindControl(container, controlId);
            if (matchControl != null)
            {
                return matchControl;
            }
            // Find in child control
            foreach (Control childControl in container.Controls)
            {
                matchControl = FindInnerControl(childControl, controlId);
                if (matchControl != null)
                {
                    return matchControl;
                }
            }
            return null;
        }
        /// <summary>
        /// Find a control in the current container && childs(FindInnerControl)
        /// If not found --> find in parent(loop)
        /// </summary>
        /// <param name="container"></param>
        /// <param name="controlId"></param>
        /// <returns></returns>
        public static Control FindOuterControl(Control container, string controlId)
        {
            if (container == null) return null;
            // Find control in the current container
            Control matchControl = FindInnerControl(container, controlId);
            // Find in parent of the current container
            if (matchControl == null)
            {
                matchControl = FindOuterControl(container.Parent, controlId);
            }
            return matchControl;
        }

        /// <summary>
        /// Find a control in the current container
        /// </summary>
        /// <param name="container"></param>
        /// <param name="controlId"></param>
        /// <returns></returns>
        public static Control FindControl(Control container, string controlId)
        {
            if (container == null) return null;
            else if (container.ID.Equals(controlId))
            {
                return container;
            }
            else
            {
                Control matchControl = container.FindControl(controlId);
                return matchControl;
            }
        }
    }
}
